package com.eien.phonezwei.broadcast;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.eien.phonezwei.service.PhoneZweiService;
import com.eien.phonezwei.utils.ApManager;
import com.eien.phonezwei.utils.LogUtil;
import com.eien.phonezwei.utils.ZUtil;

public class PhoneCallReceiver extends BroadcastReceiver {

    Context mContext;
    SharedPreferences eSharedPreferences;

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("PhoneCallReceiver", "" + intent.getAction());
        mContext = context;
        eSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        switch (intent.getAction()) {
            case Intent.ACTION_NEW_OUTGOING_CALL:
                // 如果是去电（拨出），不执行动作
                break;
            case "android.provider.Telephony.SMS_RECEIVED":
                // 收到短信

                StringBuilder sb_sms = new StringBuilder();
                Bundle bundle = intent.getExtras();
                if (bundle == null) {
                    return;
                }
                // 将带有puds字符串特征的对象取出
                Object[] myOBJpdus = (Object[]) bundle.get("pdus");
                if (myOBJpdus == null) {
                    return;
                }
                SmsMessage[] messages = new SmsMessage[myOBJpdus.length];
                String sendToNumber = eSharedPreferences.getString("sendToNumber", "");
                boolean forwardSms = true;
                for (int i = 0; i < myOBJpdus.length; i++) {
                    // 通过SmsMessage.createFromPdu()方式取出短信文字
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        String format = bundle.getString("format");
                        messages[i] = SmsMessage.createFromPdu((byte[]) myOBJpdus[i], format);
                    } else {
                        messages[i] = SmsMessage.createFromPdu((byte[]) myOBJpdus[i]);
                    }
                }

                String MsgNumber = "";
                String contact = "";
                String msgBody = "";
                for (SmsMessage currentMessage : messages) {
                    MsgNumber = currentMessage.getDisplayOriginatingAddress();
                    contact = ZUtil.getContactNameFromPhoneNum(mContext, MsgNumber);
                    msgBody = msgBody + currentMessage.getDisplayMessageBody();

                    LogUtil.i("MsgNumber=" + MsgNumber + ",sendToNumber=" + sendToNumber);

                    if (MsgNumber.equals(sendToNumber) || MsgNumber.equals("+86" + sendToNumber)) {
                        forwardSms = false;
                        String msg = msgBody.toUpperCase();
                        SharedPreferences.Editor mEditor = eSharedPreferences.edit();
                        switch (msg) {
                            case "H":
                            case "HELP":
                            case "0":
                                String help = "未接来电转发:11=开启,12=关闭,13：只转发联系人来电,14：转发所有来电\n";
                                help += "短信转发:21=开启,22=关闭\n";
                                help += "AP:31=开启,32=关闭\n";
                                sb_sms.append(help);
                                //ZUtil.sendSMS(mContext, sendToNumber, sb_sms.toString());
                                break;
                            case "11":
                                mEditor.putBoolean("forwardMissedCall", true);
                                mEditor.apply();
                                break;
                            case "12":
                                mEditor.putBoolean("forwardMissedCall", false);
                                mEditor.apply();
                                break;
                            case "13":
                                mEditor.putBoolean("contactOnly", true);
                                mEditor.apply();
                                break;
                            case "14":
                                mEditor.putBoolean("contactOnly", false);
                                mEditor.apply();
                                break;
                            case "21":
                                mEditor.putBoolean("forwardSMS", true);
                                mEditor.apply();
                                break;
                            case "22":
                                mEditor.putBoolean("forwardSMS", false);
                                mEditor.apply();
                                break;
                            case "31":
                                mEditor.putBoolean("hotspot", true);
                                mEditor.apply();
                                ApManager.configApState(mContext, true);
                                break;
                            case "32":
                                mEditor.putBoolean("hotspot", false);
                                mEditor.apply();
                                ApManager.configApState(mContext, false);
                                break;
                            case "AP":
                            case "ap":
                            case "Ap":
                                if (ApManager.isApOn(mContext)) {
                                    ApManager.configApState(mContext, false);
                                } else {
                                    ApManager.configApState(mContext, true);
                                }
                                break;
                            default:
                                break;
                        }

                        String status0 = "未接来电转发：关\n";
                        String status1 = "短信转发：关\n";
                        String status2 = "转发过滤：关\n";
                        if (eSharedPreferences.getBoolean("forwardMissedCall", false)) {
                            status0 = "未接来电转发：开\n";
                        }
                        if (eSharedPreferences.getBoolean("forwardSMS", false)) {
                            status1 = "短信转发：开\n";
                        }
                        if (eSharedPreferences.getBoolean("contactOnly", false)) {
                            status2 = "转发过滤：开\n";
                        }
                        sb_sms.append("当前状态：\n");
                        sb_sms.append(status0);
                        sb_sms.append(status1);
                        sb_sms.append(status2);
                        ZUtil.sendSMS(mContext, sendToNumber, sb_sms.toString());
                    }
                }
                if (forwardSms && eSharedPreferences.getBoolean("forwardSMS", false) && !(MsgNumber.equals(sendToNumber) || MsgNumber
                        .equals("+86" + sendToNumber))) {
                    sb_sms.append(contact);
                    sb_sms.append(MsgNumber);
                    sb_sms.append(": ");
                    sb_sms.append(msgBody);
                    String msg_sms = sb_sms.toString();
                    Log.i("PhoneCallReceiver", "转发短信 msg_sms=" + msg_sms);
                    if (sendToNumber.equals("")) {
                        Toast.makeText(mContext, "转发失败，目标手机号码不能为空！", Toast.LENGTH_LONG).show();
                    } else {
                        ZUtil.sendSMS(mContext, sendToNumber, msg_sms);
                    }
                }
                break;
            default:
                // 查了下android文档，貌似没有专门用于接收来电的action,所以，非去电即来电
                // if (eSharedPreferences.getBoolean("forwardMissedCall", false)) {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
                tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
                // 设置一个监听器
                // }
                break;
        }

    }

    // 手机状态监听器
    PhoneStateListener listener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            // state 当前状态 incomingNumber,貌似没有去电的API
            super.onCallStateChanged(state, incomingNumber);
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    // System.out.println("响铃:来电号码" + incomingNumber);
                    Log.i("PhoneCallReceiver", "listener 响铃:来电号码" + incomingNumber);
                    // 如果来电号码和转发目标号码相同，开启转发服务，用于没带手机并且忘记开服务的情况
                    if (eSharedPreferences.getString("sendToNumber", "").equals(incomingNumber)) {
                        SharedPreferences.Editor mEditor = eSharedPreferences.edit();
                        mEditor.putBoolean("forwardMissedCall", true);
                        mEditor.putBoolean("forwardSMS", true);
                        mEditor.apply();
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    // System.out.println("接听");
                    Log.i("PhoneCallReceiver", "listener 接听");
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    // System.out.println("挂断");
                    Log.i("PhoneCallReceiver", "listener 挂断");
                    if (eSharedPreferences.getBoolean("forwardMissedCall", false)) {
                        if ((eSharedPreferences.getBoolean("contactOnly", false)) && ZUtil.getContactNameFromPhoneNum(mContext,
                                incomingNumber).equals("")) {
                            // System.out.println(incomingNumber+"不是联系人号码，不转发");
                            Log.i("PhoneCallReceiver", "listener " + incomingNumber + "不是联系人号码，不转发");
                        } else {
                            // System.out.println("开始转发来自" + incomingNumber +
                            // "的未接来电");
                            Log.i("PhoneCallReceiver", "listener 开始转发来自" + incomingNumber + "的未接来电");
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    int missedCall = ZUtil.readMissedCall(mContext);
                                    if (missedCall > 0) {
                                        // System.out.println(eServiceSended +
                                        // "未接电话：" + missedCall);
                                        Intent serviceIntent = new Intent(mContext, PhoneZweiService.class);
                                        serviceIntent.setAction("com.eien.phonezwei.service.PhoneZweiService");
                                        mContext.startService(serviceIntent);
                                    }
                                }
                            }, 2000);
                        }
                    }
                    break;
            }
        }
    };

}
